//应收账单管理
//杨帆

/**
 * 总视图模型
 */
interface IReceivableBillManagentViewModel extends IBaseViewModel<IReceivableBillQueryTerms> {
    /**
     * ui-grid控制
     */
    gridOptions: uiGrid.IGridOptionsOf<ReceivableSettleBillListItemResponse>;
    /**
     * 时间日期格式
     */
    dateFormat: "{format:'YYYY.MM.DD HH:mm'}";
    /**
     * 开票状态下拉
     */
    invoiceStatusDropDown: ValueListItemResponse[];
    /**
     * 收入明细
     */
    incomeDetail: () => void;
    /**
     * 新增账单
     */
    addBill: () => void;
    /**
     * 新增账单视图
     */
    addParent: addparentViewModel;
    /**
     * 账单管理
     */
    receivableBillAdd: () => void;
    /**
     * 结算单位提示选中后的数据
     */
    settleBoxSelect: (selected: angucomplete<SettleListItemResponse>) => void;

    /**
     * 客户单位提示
     */
    searchSelect: (value: string) => any;
    /**
     * 回调函数事件
     */
    clientSelect: (selected: angucomplete<ClientListItemResponse>) => void;
    /**
     * 结算单位提示
     */
    searchSettle: (value: string) => any;
    /**
     * 收入明细按钮的显示/隐藏
     */
    receivableDis: boolean;
    /**
     * 列表高
     */
    heightA: number;
    /**
    * 防止多次点击
    */
    isDisabled: boolean;
    /**
     * 是否有权限显示导出按钮
     */
    exportbilllistShow: boolean;
    /**
     * 导出
     */
    exportbilllist: () => any;
}

/**
 * 新增账单视图模型
 */
interface addparentViewModel {
    /**
     * 总金额
     */
    totalMoney: number;
    /**
     * 应收说明
     */
    description: string;
    /**
     * 结算单位编号
     */
    settleId: string;
    /**
     * 结算单位
     */
    settle: string;
    /**
     * 客户单位
     */
    client: string;
    /**
     * 客户单位编号
     */
    clientId: string;
    /**
     * 开票日期
     */
    invoiceTime: string;
    /**
     * 开票状态
     */
    invoiceStatus: string;
    /**
     * 事件
     */
    click: () => void
}


/**
 * 查询条件
 */
interface IReceivableBillQueryTerms {
    /**
     * 应收总单编号
     */
    receivableBillId: string;
    /**
     * 结算人
     */
    reckoner: string;
    /**
     * 结算单位
     */
    settle: string;
    /**
     * 应收总额
     */
    receivableTotalPrice: string;
    /**
     * 发货起始时间
     */
    deliveryTime: string;
    /**
     * 发货结束时间
     */
    endTime: string;
    /**
     * 客户单位
     */
    clientName: string;
    /**
     * 开票状态
     */
    invoiceStatus: string
}



class IReceivableBillManagentController extends ListController<IReceivableBillManagentViewModel, IReceivableBillQueryTerms>{
    gridApi: uiGrid.IGridApiOf<ReceivableSettleBillListItemResponse>;
    orderBy: number = 0;
    /**
     * 排序
     */
    asc: boolean = true;
    /**
     * 单选
     */
    selectReceivableBill: ReceivableSettleBillListItemResponse;
    /**
     * 收入明细按钮的显示/隐藏
     */
    receivableDis = false;


    constructor($scope: IReceivableBillManagentViewModel, private receivableService: IReceivableService, private $ngBootbox: BootboxService, private $timeout: ng.ITimeoutService,
        private valueService: IValueService, private $state: angular.ui.IStateService, private clientService: IClientService,
        private settleService: ISettleService, private authorizationService: IAuthorizationService, private $location: ng.ILocationService,private exportService: exportService) {
        super($scope);
        this.init();
    }

    /**
     * 初始化
     */
    init(): void {
        super.init();
        this.$scope.exportbilllistShow = false;

        this.$scope.queryTerms = {
            receivableBillId: "",
            reckoner: "",
            settle: "",
            receivableTotalPrice: "",
            deliveryTime: "",
            endTime: "",
            clientName: "",
            invoiceStatus: ""
        }

        this.$scope.gridOptions = {
            multiSelect: false,//单选
            enableSelectAll: false,//全选禁用
            paginationPageSizes: [10, 20, 30],
            useExternalPagination: true,
            useExternalSorting: true,
            enableColumnResizing: true,
            enableFullRowSelection: true,
            columnDefs: [
                { displayName: "应收总编号", field: 'billCode', enableColumnMenu: false, cellTooltip: true, headerTooltip: true },
                { displayName: "结算单位", field: 'settle', enableColumnMenu: false, cellTooltip: true, headerTooltip: true },
                { displayName: "应收总额", field: 'totalMoney', enableColumnMenu: false, cellTooltip: true, headerTooltip: true },
                { displayName: '结算人', field: 'reckoner', enableColumnMenu: false, cellTooltip: true, headerTooltip: true },
                { displayName: '结算日期', field: 'creationTime', enableColumnMenu: false, cellTooltip: true, headerTooltip: true },
                { displayName: '开票状态', field: 'invoiceStatus', enableColumnMenu: false, cellTooltip: true, headerTooltip: true }
            ],
            onRegisterApi: (gridApi) => {
                gridApi.pagination.on.paginationChanged(this.$scope,(skipSize,pageSize)=>{
                    this.paginationChanged(skipSize,pageSize,this.$state);
                });
                // gridApi.pagination.on.paginationChanged(this.$scope, this.paginationChanged);
                gridApi.core.on.sortChanged(this.$scope, this.sortChange);
                gridApi.selection.on.rowSelectionChanged(this.$scope, this.selectChange);
            }
        };

        $('#openinvoiceTime').click(() => {
            $('#invoiceTime').datetimepicker('show');
        });
        $('#openstarttime').click(() => {
            $('#starttime').datetimepicker('show');
        });
        $('#openendtime').click(() => {
            $('#endtime').datetimepicker('show');
        });

        this.query();
        this.loadInvoiceStatusDropDown();
        this.$scope.incomeDetail = this.incomeDetail;
        this.$scope.receivableBillAdd = this.receivableBillAdd;
        this.$scope.addBill = this.showAddBillDialog;

        this.$scope.searchSelect = this.searchSelect;
        this.$scope.settleBoxSelect = this.settleBoxSelect;
        this.$scope.searchSettle = this.searchSettle;
        this.$scope.clientSelect = this.clientSelect;
        this.$scope.exportbilllist = this.exportbilllist;

        this.$scope.isDisabled = false;
        /**
         *  应收收入权限——收入明细的显示、隐藏
         */
        this.authorizationService.auth('25B5C4744B62B2487505ED240CCADD8443A4C94ED9C4394C658D5F98BA304405').then((res) => {
            this.$scope.receivableDis = res.data.extData;
        })

        this.authorizationService.auth('25B5C4744B62B24879F8E2412FD7767493A952627A939FEDF3D2F6F4A304983264CC74A5FBB72AC23BB4F625665A1DE3').then((res) => {
            this.$scope.exportbilllistShow = res.data.extData;
        })

    }

    localHistory(): void {
        super.localHistory(this.$state)
    }
    getHistory(): void {
        super.getHistory(this.$state, this.$location)
    }

    /**
     * 加载数据
     */
    loadData(queryTerms: IReceivableBillQueryTerms, skip: number, count: number): void {
        this.receivableService.getreceivableSettleBillList(this.orderBy.toString(), this.asc, queryTerms.receivableBillId, queryTerms.reckoner, queryTerms.settle, queryTerms.receivableTotalPrice,
            queryTerms.deliveryTime, queryTerms.endTime, "", "", queryTerms.invoiceStatus, queryTerms.clientName, "","", skip, count).then((result) => {
                this.$scope.gridOptions.totalItems = result.data.total;
                this.$scope.gridOptions.data = result.data.data;

                this.$scope.heightA = (this.$scope.gridOptions.data.length * 39) + 95;

                if (skip == 0) {
                    this.$scope.gridOptions.paginationCurrentPage = 1;
                }
                this.$scope.querying = false;
            }, error => {
                this.$scope.querying = false;
            });

    }

    /**
     * 开票状态下拉
     */
    loadInvoiceStatusDropDown(): void {
        this.$scope.invoiceStatusDropDown = this.valueService.getInvoiceStatusList().data;
    }

    /**
     * 排序事件触发
     */
    sortChange = (grid: uiGrid.IGridInstanceOf<ReceivableSettleBillListItemResponse>, sortColumns: Array<uiGrid.IGridColumnOf<ReceivableSettleBillListItemResponse>>) => {
        if (sortColumns.length == 0) {
            this.reload();
        } else {
            let sortItem = sortColumns[0];
            switch (sortItem.name) {
                case "billCode": {
                    this.orderBy = 1;
                } break;
                case "settle": {
                    this.orderBy = 2;
                } break;
                case "totalMoney": {
                    this.orderBy = 3;
                } break;
                case "reckoner": {
                    this.orderBy = 4;
                } break;
                case "creationTime": {
                    this.orderBy = 5;
                } break;
                case "invoiceStatus": {
                    this.orderBy = 6;
                } break;
            }
            this.asc = sortItem.sort.direction == "asc";
            this.reload();
        }
    }

    /**
     * 单选
     */
    selectChange = (row: uiGrid.IGridRowOf<ReceivableSettleBillListItemResponse>) => {
        if (row.isSelected == true) {
            this.selectReceivableBill = row.entity;
        } else {
            this.selectReceivableBill = null;
        }
    };

    /**
     * 收入明细
     */
    incomeDetail = () => {
        if (!this.selectReceivableBill) {
            this.$ngBootbox.alert("请选择一项");
            return;
        };
        this.$state.go('app.receivable.income_detail', { id: this.selectReceivableBill.settleId, name: this.selectReceivableBill.settle });
    };

    /**
     * 账单管理
     */
    receivableBillAdd = () => {
        if (!this.selectReceivableBill) {
            this.$ngBootbox.alert("请选择一项");
            return;
        };
        this.$state.go('app.receivable.bill_admin', { id: this.selectReceivableBill.id });
    };

    /**
     * 新增账单
     */
    showAddBillDialog = () => {
        this.$scope.title = "新增账单";
        $("#settleBox_value").val(""),
            $("#client_value").val(""),
            // $("#invoiceTime").val(""),
            this.$scope.addParent = {
                totalMoney: null,
                description: "",
                settleId: "",
                settle: "",
                client: "",
                clientId: "",
                invoiceTime: "",
                invoiceStatus: "",
                click: this.addBill
            };
    }

    /**
     * 新增账单——保存
     */
    addBill = () => {
        let validShow = $('#formBill').valid();
        if (!validShow) { return; };
        this.$scope.isDisabled = true;
        this.$timeout(() => {
            this.$scope.isDisabled = false
        },1000)
        this.$ngBootbox.confirm("确定保存数据吗？").then(res => {

            this.receivableService.addparent(
                this.$scope.addParent.totalMoney,
                this.$scope.addParent.description,
                this.$scope.addParent.settleId,
                $("#settleBox_value").val(),
                $("#client_value").val(),
                this.$scope.addParent.clientId,
                $("#invoiceTime").val(),
                this.$scope.addParent.invoiceStatus
            ).then((res) => {
                this.$ngBootbox.alert("保存成功！");
                this.reload();
                $('#orderAdd').modal('hide');//关闭弹窗
            });
        });
    }

    /**
     * 结算单位提示选中后的数据
     */
    settleBoxSelect = (selected: angucomplete<SettleListItemResponse>) => {
        if (selected) {
            this.$scope.addParent.settleId = selected.description.id;
        }
    }

    /**
     * 客户单位提示
     */
    searchSelect = (value: string) => {
        return this.clientService.getList(value, "", "", "","", "", 0, 5).then((res) => {
            return res.data.data;
        })
    }

    /**
     * 回调函数
     */
    clientSelect = (selected: angucomplete<ClientListItemResponse>) => {
        if (selected) {
            this.$scope.addParent.clientId = selected.description.id;
            this.searchSettle;
        }
    }
    /**
     *  结算单位提示
     */
    searchSettle = (value: string) => {
        return this.settleService.getList(this.$scope.addParent.clientId, value, "", true, 0, 5).then((res) => {
            return res.data.data;
        });
    }

    exportbilllist=()=> {
        if(this.$scope.gridOptions.totalItems>30000){
            this.$ngBootbox.alert('导出数据不可超过3万条');
            return
        }else{
            this.exportService.exportbilllist(this.orderBy,this.asc,this.$scope.queryTerms.receivableBillId,this.$scope.queryTerms.reckoner,this.$scope.queryTerms.settle,this.$scope.queryTerms.receivableTotalPrice,
                this.$scope.queryTerms.deliveryTime,this.$scope.queryTerms.endTime,"","",this.$scope.queryTerms.invoiceStatus,this.$scope.queryTerms.clientName,"")
        }

        
    }


}

angular.module("tms").controller("receivableBillController", ["$scope", "receivableService", "$ngBootbox", "$timeout", "valueService", "$state", "clientService", "settleService", "authorizationService", "$location","exportService", IReceivableBillManagentController]);